package com.example.distributelock.controller;

import com.example.distributelock.dao.DistributeLockMapper;
import com.example.distributelock.model.DistributeLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class DatabaseLockController {

    public static final Logger log = LoggerFactory.getLogger(DatabaseLockController.class);

    @Resource
    private DistributeLockMapper distributeLockMapper;

    @RequestMapping("distributeLockByDB")
    @Transactional(rollbackFor = Exception.class) // spring默认的回滚异常是RuntimeException，这样想自定义的异常throw new Exception("分布式锁找不到");是不会回滚的
    public String distributeLockByDB() throws Exception {
        log.info("我进入了方法！");
        DistributeLock distributeLock = distributeLockMapper.selectDistributeLock("demo");
        if (distributeLock == null)
            throw new Exception("分布式锁找不到");
        log.info("我进入了锁！");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "我已经执行完成！";
    }

}
